import requests
# import time
import json
from openpyxl import Workbook


def insert2excel(allinfo):
    try:
        # 表头
        tableTitle = ['名称', '时间', '经度', '纬度', '中心气压(hPa)', '风速(m/s)', '移向', '移速(m/s)']
        wb = Workbook()
        ws = wb.active
        ws.title = 'sheet1'
        ws.append(tableTitle)
        for info in allinfo:
            ws.append(info)
        wb.save("typhoon.xlsx")
        return True
    except:
        return False


def get_tp_data(year, code):
    # tim = int(time.time())
    # https://d1.weather.com.cn/typhoon/typhoon_data/2022/2212.json?callback=getData&_=1664609878837
    url = f'http://d1.weather.com.cn/typhoon/typhoon_data/{year}/{code}.json?callback=getData&_=1664609878837'
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) '
                             'Chrome/55.0.2883.87 Safari/537.36',
               'Referer': 'http://typhone.weather.com.cn/'}
    r = requests.get(url, headers=headers)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    datas = json.loads(r.text[8:-1])
    tp_name = datas['typhoon'][2]
    detail_datas = datas['typhoon'][8]
    # 台风信息
    allinfo = []
    for data in detail_datas:
        # 时间
        tp_time = data[1]
        # 经度
        tp_lon = data[4]
        # 纬度
        tp_lat = data[5]
        # 中心气压
        central_pressure = data[6]
        # 风速
        tp_speed = data[7]
        # 移向
        tp_direction = data[8]
        # 去除台风登陆时的空行
        # 移速
        move_speed = data[9]
        tp_info = [f'{code}-' + tp_name, tp_time, tp_lon, tp_lat, central_pressure, tp_speed, tp_direction, move_speed]
        allinfo.append(tp_info)
    insert2excel(allinfo)


get_tp_data(2022, 2212)